﻿using SameGame.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SameGame.Presentation.Presenters
{
	class BallBoardStatePresenter : IBoardBallsStatisticPresenter
	{
		private IBoard _board;
		private IBoardBallsStatisticView _view;

		public BallBoardStatePresenter(IBoard _board)
		{
			this._board = _board;
		}

		public IBoardBallsStatisticView View
		{
			get
			{
				return _view;
			}
			set
			{
				_view = value;
				if (_view != null)
				{
					InitView();
				}
			}
		}

		private void InitView()
		{
			_board.ItemsChanged += _board_ItemsChanged;
			_board.BoardInited += _board_BoardInited;
		}

		void _board_BoardInited(object sender, EventArgs e)
		{
			ReloadView();
		}

		void _board_ItemsChanged(object sender, EventArgs e)
		{
			ReloadView();
		}

		private void ReloadView()
		{
			SortedDictionary<int, int> colors = new SortedDictionary<int, int>();
			foreach (CItem item in _board.getAllItems())
			{
				if (item != null)
				{
					if (colors.ContainsKey(item._color))
					{
						colors[item._color] += 1;
					}
					else
					{
						colors.Add(item._color, 1);
					}
				}
			}

			_view.SetColorStatistic(colors);
		}
	}
}
